package canss.webservice.servlets;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.beehive.controls.api.bean.Control;


import canss.supports.basic;
import canss.webservice.model.EventDescription;
import canss.webservice.model.Feed;
import canss.webservice.service.PortalIntraWebServiceControl;
import canss.webservice.service.PortalIntraWebServiceControlBean;

public class svtTRAdminFeed extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet
{
	private static final long serialVersionUID = 7885452414928382127L;

	public svtTRAdminFeed()
	{
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doPost(request, response);
	}

	@Control
	PortalIntraWebServiceControl control; // control = (control==null)?new

	// PortalIntraWebServiceControlBean():control;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setContentType("text/html; charset=UTF-8");

		PrintWriter out = response.getWriter();

		String _pid = request.getParameter("_pid");
		String _notxml = request.getParameter("_notxml");

		control = (control == null) ? new PortalIntraWebServiceControlBean() : control;
		Feed[] feedByMultiple = control.getFeedByMultiple(_pid, null);

		if (_notxml != null)
		{// in html
		} else
		{// in xml
			out.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
			weblogic.application.utils.XMLWriter writer = new weblogic.application.utils.XMLWriter(out);

			writer.addElement("canss");

			if (feedByMultiple == null || feedByMultiple.length == 0)
			{
				writer.addElement("canssPerson_Person");
				writer.addElement("canssPerson_id", basic.var2str(_pid));
				writer.addEmptyElement("canssFeed_feedlist");
				writer.closeElement();
			} else
			{
				boolean ischanged = false;
				String lastpid = "";

				for (Feed feed : feedByMultiple)
				{
					if (!lastpid.equals(basic.var2str(feed.getTBLPID_PID())))
					{
						lastpid = basic.var2str(feed.getTBLPID_PID());
						ischanged = true;
					}

					if (ischanged)
					{
						writer.addElement("canssPerson_Person");
						writer.addElement("canssPerson_id", basic.var2str(feed.getTBLPID_PID()));
						writer.addElement("canssFeed_feedlist");
					}
					writer.addElement("canssFeed_feed");
					writer.addElement("canssTrace_ProviderModuleID", basic.var2str(feed.getTBLMID_MID()));
					writer.addElement("canssTrace_feeduri", basic.var2str(feed.getFEEDURI()));
					writer.addElement("canssTrace_ruleid", basic.var2str(feed.getRULEID()));
					writer.addElement("canssTrace_rulename", getRuleName(basic.var2str(feed.getRULEID())));
					writer.addElement("canssTrace_feedstatus", basic.var2str(feed.getFEEDSTATUS()));
					EventDescription retevent = control.getEventDescByEventID(feed.getFEEDSTATUS());
					if (retevent != null && retevent.getONELINEDESC() != null)
					{
						writer.addElement("canssTrace_feedstatusdesc", retevent.getONELINEDESC());
					}
					writer.closeElement();
					if (ischanged)
					{
						writer.closeElement();
						writer.closeElement();
					}
				}

			}

			writer.finish();
		}
	}
	
	private static final String outUrl = "http://mediator.canss.net/ServiceManager/getRuleNameByRID.php";
	public static String getRuleName(String RuleID)
	{
		if(!basic.isEmpty(RuleID))
		{
			HttpURLConnection conn = null;
			DataOutputStream out0 = null;
			BufferedReader reader = null;
			try
			{
				URL server = new URL(outUrl);
				conn = (HttpURLConnection)server.openConnection();
				//
				// header
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
				//
				//query
				out0 = new DataOutputStream(conn.getOutputStream());
				out0.writeBytes("RID="+RuleID.trim());
				out0.flush();
				out0.close(); out0=null;
				//
				//get result
				StringBuffer outbuf = new StringBuffer();
				InputStream in = conn.getInputStream();
				reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
				String line = null;
				while ((line = reader.readLine()) != null)
					outbuf.append(line + "\n");
				reader.close(); reader=null;
				//
				//return
				return outbuf.toString().trim(); 
			} catch (MalformedURLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ProtocolException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally
			{
				try
				{
					if(reader!=null)
						reader.close();
					if(out0!=null)
						out0.close();
					if(conn!=null)
						conn.disconnect();
				}catch(Exception ee)
				{}
			}
		}
		return "";
	}
}